package com.wsq.mvvm

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.databinding.ObservableField
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.wsq.mvvm.bind.MainActivityBinding
//import com.wsq.mvvm.databinding.MainActivityBinding

import com.wsq.mvvm.model.Student
import com.wsq.mvvm.viewmodel.MainViewModel
import kotlinx.android.synthetic.main.activity_main.*

/**
 * 目标：
 * 1.实现mvvm框架
 * 2.使用databinding、livedata、ViewModel之间的衔接
 *
 * databinding使用流程：
 *
 *
 */
class MainActivity : AppCompatActivity() {

    /**
     * viewModels() 函数来自于 "androidx.activity:activity-ktx:1.1.0" 库
     * 本质是一个ComponentActivity的扩展函数
     */
    private val model:MainViewModel by viewModels()

    var num: Int = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        /**
         * MainActivityBinding是编译器生成的，已经在布局文件中声明；
         * 如果不在布局文件中声明，则编译系统会自动生成一个类
         */
        val binding:MainActivityBinding = DataBindingUtil.setContentView(this
            , R.layout.activity_main)

//        model = ViewModelProvider(this)


        binding.viewModel = model

        // LiveData需要lifecycle owner
        binding.lifecycleOwner = this

        Toast.makeText(this, "num:" + num, Toast.LENGTH_SHORT).show()



    }

    /**
     * 使用databinding的最简单的demo
     */
    private fun method1(){
        val student = Student()
        //将实例化的数据，binding到布局文件中声明过的对象上去
//        binding.student = student
        //为实例数据赋值
        student.name.set("lisi")
        student.id.set(12)

        val nameObserver = Observer<String>{
            nameTextView.text = it
        }

        model.currentName.observe(this, nameObserver)

        changNameBtn.setOnClickListener{

            val name = "xiaopangzhi" + ++num
//            model.currentName.value
        }
    }
}